using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text.Json;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 增强的世界设定管理器 - 确保在章节生成前所有必要设定都已生成
    /// </summary>
    public class EnhancedWorldSettingManager
    {
        private readonly ILogger<EnhancedWorldSettingManager> _logger;
        private readonly WorldSettingService _worldSettingService;
        private readonly IAIService _aiService;

        public EnhancedWorldSettingManager(
            ILogger<EnhancedWorldSettingManager> logger,
            WorldSettingService worldSettingService,
            IAIService aiService)
        {
            _logger = logger;
            _worldSettingService = worldSettingService;
            _aiService = aiService;
        }

        /// <summary>
        /// 确保章节生成前所有必要设定都已生成
        /// </summary>
        public async Task<WorldSettingCompletionResult> EnsureChapterSettingsCompleteAsync(
            string projectPath,
            int chapterNumber,
            string creativeDirection,
            string overallOutline,
            VolumeOutline? currentVolume = null)
        {
            try
            {
                _logger.LogInformation($"检查第{chapterNumber}章所需的世界设定完整性");

                var result = new WorldSettingCompletionResult
                {
                    ChapterNumber = chapterNumber,
                    CheckedAt = DateTime.Now
                };

                // 检查基础世界设定
                var basicSettings = await CheckBasicWorldSettingsAsync(projectPath);
                result.BasicSettingsComplete = basicSettings.IsComplete;
                result.MissingBasicSettings.AddRange(basicSettings.MissingSettings);

                // 检查详细设定
                var detailedSettings = await CheckDetailedSettingsAsync(projectPath, chapterNumber, currentVolume);
                result.DetailedSettingsComplete = detailedSettings.IsComplete;
                result.MissingDetailedSettings.AddRange(detailedSettings.MissingSettings);

                // 如果有缺失的设定，自动生成
                if (!result.BasicSettingsComplete || !result.DetailedSettingsComplete)
                {
                    _logger.LogInformation($"发现缺失的设定，开始自动生成...");
                    await GenerateMissingSettingsAsync(projectPath, result, creativeDirection, overallOutline);
                }

                result.IsComplete = result.BasicSettingsComplete && result.DetailedSettingsComplete;
                
                _logger.LogInformation($"第{chapterNumber}章世界设定检查完成，完整性: {result.IsComplete}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查第{chapterNumber}章世界设定失败");
                return new WorldSettingCompletionResult
                {
                    ChapterNumber = chapterNumber,
                    IsComplete = false,
                    ErrorMessage = ex.Message,
                    CheckedAt = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 检查基础世界设定
        /// </summary>
        private async Task<SettingCheckResult> CheckBasicWorldSettingsAsync(string projectPath)
        {
            var result = new SettingCheckResult();
            var settingsPath = Path.Combine(projectPath, "世界观设定");

            var basicSettingFiles = new[]
            {
                "世界观设定管理.md",
                "修炼体系设定管理.md",
                "角色设定管理.md",
                "关系网络.md",
                "地图结构管理.md"
            };

            foreach (var fileName in basicSettingFiles)
            {
                var filePath = Path.Combine(settingsPath, fileName);
                if (!File.Exists(filePath) || (await File.ReadAllTextAsync(filePath)).Length < 100)
                {
                    result.MissingSettings.Add(fileName.Replace(".md", ""));
                }
            }

            result.IsComplete = !result.MissingSettings.Any();
            return result;
        }

        /// <summary>
        /// 检查详细设定
        /// </summary>
        private async Task<SettingCheckResult> CheckDetailedSettingsAsync(
            string projectPath, 
            int chapterNumber, 
            VolumeOutline? currentVolume)
        {
            var result = new SettingCheckResult();
            var settingsPath = Path.Combine(projectPath, "世界观设定");

            // 根据章节进度确定需要的详细设定
            var requiredDetailedSettings = DetermineRequiredDetailedSettings(chapterNumber, currentVolume);

            foreach (var settingName in requiredDetailedSettings)
            {
                var fileName = $"{settingName}.md";
                var filePath = Path.Combine(settingsPath, fileName);
                
                if (!File.Exists(filePath))
                {
                    result.MissingSettings.Add(settingName);
                }
                else
                {
                    var content = await File.ReadAllTextAsync(filePath);
                    if (content.Length < 200) // 内容太少认为不完整
                    {
                        result.MissingSettings.Add(settingName);
                    }
                }
            }

            result.IsComplete = !result.MissingSettings.Any();
            return result;
        }

        /// <summary>
        /// 确定章节所需的详细设定
        /// </summary>
        private List<string> DetermineRequiredDetailedSettings(int chapterNumber, VolumeOutline? currentVolume)
        {
            var requiredSettings = new List<string>();

            // 前期章节需要的设定
            if (chapterNumber <= 5)
            {
                requiredSettings.AddRange(new[]
                {
                    "势力管理",
                    "功法体系管理",
                    "武器管理",
                    "装备体系管理"
                });
            }

            // 中期章节需要的设定
            if (chapterNumber > 5 && chapterNumber <= 20)
            {
                requiredSettings.AddRange(new[]
                {
                    "秘境管理",
                    "灵宝体系管理",
                    "政治体系管理",
                    "商业体系管理"
                });
            }

            // 后期章节需要的设定
            if (chapterNumber > 20)
            {
                requiredSettings.AddRange(new[]
                {
                    "维度结构管理",
                    "司法体系管理",
                    "职业体系管理",
                    "货币体系管理"
                });
            }

            // 根据卷宗内容确定特殊需求
            if (currentVolume != null)
            {
                var volumeDescription = currentVolume.Description.ToLower();
                
                if (volumeDescription.Contains("秘境") || volumeDescription.Contains("探险"))
                {
                    requiredSettings.Add("秘境管理");
                }
                
                if (volumeDescription.Contains("势力") || volumeDescription.Contains("宗门") || volumeDescription.Contains("战争"))
                {
                    requiredSettings.Add("势力管理");
                    requiredSettings.Add("政治体系管理");
                }
                
                if (volumeDescription.Contains("功法") || volumeDescription.Contains("修炼") || volumeDescription.Contains("突破"))
                {
                    requiredSettings.Add("功法体系管理");
                    requiredSettings.Add("修炼体系设定管理");
                }
            }

            return requiredSettings.Distinct().ToList();
        }

        /// <summary>
        /// 生成缺失的设定
        /// </summary>
        private async Task GenerateMissingSettingsAsync(
            string projectPath,
            WorldSettingCompletionResult result,
            string creativeDirection,
            string overallOutline)
        {
            var settingsPath = Path.Combine(projectPath, "世界观设定");
            Directory.CreateDirectory(settingsPath);

            // 生成缺失的基础设定
            foreach (var missingSetting in result.MissingBasicSettings)
            {
                try
                {
                    _logger.LogInformation($"生成基础设定: {missingSetting}");
                    var content = await GenerateBasicSettingContentAsync(missingSetting, creativeDirection, overallOutline);
                    var filePath = Path.Combine(settingsPath, $"{missingSetting}.md");
                    await File.WriteAllTextAsync(filePath, content);
                    result.GeneratedSettings.Add(missingSetting);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"生成基础设定失败: {missingSetting}");
                    result.FailedSettings.Add(missingSetting);
                }
            }

            // 生成缺失的详细设定
            foreach (var missingSetting in result.MissingDetailedSettings)
            {
                try
                {
                    _logger.LogInformation($"生成详细设定: {missingSetting}");
                    var content = await GenerateDetailedSettingContentAsync(missingSetting, creativeDirection, overallOutline);
                    var filePath = Path.Combine(settingsPath, $"{missingSetting}.md");
                    await File.WriteAllTextAsync(filePath, content);
                    result.GeneratedSettings.Add(missingSetting);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"生成详细设定失败: {missingSetting}");
                    result.FailedSettings.Add(missingSetting);
                }
            }

            // 更新完整性状态
            result.BasicSettingsComplete = !result.MissingBasicSettings.Except(result.GeneratedSettings).Any();
            result.DetailedSettingsComplete = !result.MissingDetailedSettings.Except(result.GeneratedSettings).Any();
        }

        /// <summary>
        /// 生成基础设定内容
        /// </summary>
        private async Task<string> GenerateBasicSettingContentAsync(string settingName, string creativeDirection, string overallOutline)
        {
            var prompt = settingName switch
            {
                "世界观设定管理" => BuildWorldViewPrompt(creativeDirection, overallOutline),
                "修炼体系设定管理" => BuildCultivationSystemPrompt(creativeDirection, overallOutline),
                "角色设定管理" => BuildCharacterSettingPrompt(creativeDirection, overallOutline),
                "关系网络" => BuildRelationshipNetworkPrompt(creativeDirection, overallOutline),
                "地图结构管理" => BuildMapStructurePrompt(creativeDirection, overallOutline),
                _ => BuildGenericSettingPrompt(settingName, creativeDirection, overallOutline)
            };

            return await _aiService.GenerateTextAsync(prompt, 3000, 0.8f);
        }

        /// <summary>
        /// 生成详细设定内容
        /// </summary>
        private async Task<string> GenerateDetailedSettingContentAsync(string settingName, string creativeDirection, string overallOutline)
        {
            var prompt = settingName switch
            {
                "势力管理" => BuildFactionManagementPrompt(creativeDirection, overallOutline),
                "功法体系管理" => BuildTechniqueSystemPrompt(creativeDirection, overallOutline),
                "秘境管理" => BuildSecretRealmPrompt(creativeDirection, overallOutline),
                "武器管理" => BuildWeaponManagementPrompt(creativeDirection, overallOutline),
                "装备体系管理" => BuildEquipmentSystemPrompt(creativeDirection, overallOutline),
                "灵宝体系管理" => BuildTreasureSystemPrompt(creativeDirection, overallOutline),
                "政治体系管理" => BuildPoliticalSystemPrompt(creativeDirection, overallOutline),
                "商业体系管理" => BuildBusinessSystemPrompt(creativeDirection, overallOutline),
                "维度结构管理" => BuildDimensionStructurePrompt(creativeDirection, overallOutline),
                "司法体系管理" => BuildJudicialSystemPrompt(creativeDirection, overallOutline),
                "职业体系管理" => BuildProfessionalSystemPrompt(creativeDirection, overallOutline),
                "货币体系管理" => BuildCurrencySystemPrompt(creativeDirection, overallOutline),
                _ => BuildGenericDetailedSettingPrompt(settingName, creativeDirection, overallOutline)
            };

            return await _aiService.GenerateTextAsync(prompt, 2500, 0.8f);
        }

        #region 提示词构建方法

        private string BuildWorldViewPrompt(string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的世界观设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成包含以下内容的世界观设定：
1. 世界基本构造和物理法则
2. 历史背景和重大事件
3. 文明发展程度和科技水平
4. 魔法/修炼体系的基本原理
5. 世界的独特特征和规则

要求：内容详细且逻辑自洽，为后续剧情发展提供坚实基础。";
        }

        private string BuildCultivationSystemPrompt(string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的修炼体系设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成包含以下内容的修炼体系：
1. 修炼等级划分和名称
2. 每个等级的特征和能力
3. 突破条件和方法
4. 修炼资源和辅助物品
5. 修炼的风险和限制

要求：体系完整，层次分明，符合故事设定。";
        }

        private string BuildCharacterSettingPrompt(string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的角色设定管理：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成包含以下内容的角色设定：
1. 主要角色列表和基本信息
2. 角色背景和性格特征
3. 角色能力和特长
4. 角色目标和动机
5. 角色发展轨迹规划

要求：角色鲜明，各有特色，符合剧情需要。";
        }

        private string BuildFactionManagementPrompt(string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的势力管理设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成包含以下内容的势力设定：
1. 主要势力列表和基本信息
2. 势力结构和等级制度
3. 势力间的关系和冲突
4. 势力的资源和实力
5. 势力的发展目标和策略

要求：势力体系完整，关系复杂但清晰，为剧情冲突提供基础。";
        }

        private string BuildSecretRealmPrompt(string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的秘境管理设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成包含以下内容的秘境设定：
1. 秘境列表和基本信息
2. 秘境的开启条件和规则
3. 秘境内的挑战和机遇
4. 秘境的历史和传说
5. 秘境对剧情发展的作用

要求：秘境设定丰富，各有特色，为冒险情节提供支撑。";
        }

        private string BuildGenericSettingPrompt(string settingName, string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的{settingName}设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请生成与{settingName}相关的详细设定，包括：
1. 基本概念和定义
2. 具体规则和机制
3. 与其他设定的关联
4. 在故事中的作用
5. 发展变化的可能性

要求：设定完整，逻辑自洽，符合整体世界观。";
        }

        private string BuildGenericDetailedSettingPrompt(string settingName, string creativeDirection, string overallOutline)
        {
            return $@"基于以下信息生成详细的{settingName}设定：

创作方向：{creativeDirection}

全书大纲：
{overallOutline}

请为{settingName}生成详细的管理设定，包括：
1. 详细分类和层级结构
2. 具体实例和案例
3. 运作机制和规则
4. 与主线剧情的关联
5. 对角色发展的影响

要求：内容丰富，实用性强，为具体章节创作提供参考。";
        }

        // 其他提示词构建方法...
        private string BuildRelationshipNetworkPrompt(string creativeDirection, string overallOutline) => BuildGenericSettingPrompt("关系网络", creativeDirection, overallOutline);
        private string BuildMapStructurePrompt(string creativeDirection, string overallOutline) => BuildGenericSettingPrompt("地图结构管理", creativeDirection, overallOutline);
        private string BuildTechniqueSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("功法体系管理", creativeDirection, overallOutline);
        private string BuildWeaponManagementPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("武器管理", creativeDirection, overallOutline);
        private string BuildEquipmentSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("装备体系管理", creativeDirection, overallOutline);
        private string BuildTreasureSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("灵宝体系管理", creativeDirection, overallOutline);
        private string BuildPoliticalSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("政治体系管理", creativeDirection, overallOutline);
        private string BuildBusinessSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("商业体系管理", creativeDirection, overallOutline);
        private string BuildDimensionStructurePrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("维度结构管理", creativeDirection, overallOutline);
        private string BuildJudicialSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("司法体系管理", creativeDirection, overallOutline);
        private string BuildProfessionalSystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("职业体系管理", creativeDirection, overallOutline);
        private string BuildCurrencySystemPrompt(string creativeDirection, string overallOutline) => BuildGenericDetailedSettingPrompt("货币体系管理", creativeDirection, overallOutline);

        #endregion
    }

    /// <summary>
    /// 世界设定完整性检查结果
    /// </summary>
    public class WorldSettingCompletionResult
    {
        public int ChapterNumber { get; set; }
        public bool IsComplete { get; set; }
        public bool BasicSettingsComplete { get; set; }
        public bool DetailedSettingsComplete { get; set; }
        public List<string> MissingBasicSettings { get; set; } = new();
        public List<string> MissingDetailedSettings { get; set; } = new();
        public List<string> GeneratedSettings { get; set; } = new();
        public List<string> FailedSettings { get; set; } = new();
        public string? ErrorMessage { get; set; }
        public DateTime CheckedAt { get; set; }
    }

    /// <summary>
    /// 设定检查结果
    /// </summary>
    public class SettingCheckResult
    {
        public bool IsComplete { get; set; }
        public List<string> MissingSettings { get; set; } = new();
    }
}
